<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 20:04:48
 * @Description  : 角色管理
-->
<template>
  <div class="bg-lightColor role-con p-3 rounded" v-if="editModel === 'view'">
    <n-grid
      x-gap="12"
      :cols="1"
      class="mb-2"
      v-permission="[PERMISSIONS.ROLE_EDIT]"
    >
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="handleToAdd"
        >
          <SvgIcon
            icon="zengjiatianjiajiahao"
            color="#badeff"
            class="mr-1"
          ></SvgIcon>
          新增
        </n-button>
      </n-gi>
    </n-grid>
    <wp-data-table
      v-loading="loading"
      :data="data"
      :checked-row-keys="checkedRowKeys"
      :columns="columns"
      @page-change="handlePageChange"
      @select-change="handleSelectChange"
      @order-change="handleOrderChange"
      :pages="pageResultInfo.pages"
      :total="pageResultInfo.total"
    >
    </wp-data-table>
  </div>
  <create-and-update-role
    @change-role="handleAddAndUpdateRole"
    :is-modify="editModel === 'update'"
    :role-res="curRole"
    v-else
    @back-view="editModel = 'view'"
  ></create-and-update-role>
</template>

<script setup lang="ts">
import { useMessage, NButton, useDialog } from 'naive-ui'
import type { DataTableColumn, DataTableColumns } from 'naive-ui'
import useUserStore from '@/stores/modules/user'
import useRoleStore from '@/stores/modules/role'
import {
  getRoleByPage,
  updateRole,
  createRole,
  delRole,
  sortRole
} from '@/api/role'
import type {
  RoleCreateReq,
  RoleRowData,
  RoleUpdateReq,
  RoleRes
} from '@/types/role'
import { formatTime } from '@/utils/index'
import {
  renderRoleLabel,
  renderSort,
  renderSystemLabel
} from '@/utils/commonBusiness'
import { load } from '@/utils/loading'
import { PERMISSIONS } from '@/constants/permission'
import SvgIcon from '@/components/SvgIcon/index.vue'
import WpDataTable from '@/components/WpDataTable/index.vue'
import PicValidCode from '@/components/PicValidCode/index.vue'
import CreateAndUpdateRole from './components/CreateAndUpdateRole.vue'

const userStore = useUserStore()
const roleStore = useRoleStore()
const message = useMessage()
const dialog = useDialog()
const data = ref<RoleRowData[]>([])
const pageInfo = reactive({
  page: 1,
  pageSize: 50,
  type: 0
})

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})
const loading = ref(false)

const createColumns = (): DataTableColumns<RoleRowData> => {
  const selectColumn: DataTableColumn<RoleRowData> = {
    type: 'selection',
    minWidth: 30,
    width: 30
  }

  const actionColumn: DataTableColumn<RoleRowData> = {
    title: '操作',
    key: 'actions',
    minWidth: 120,
    width: 120,
    render(row) {
      return h('div', [
        h(
          NButton,
          {
            text: true,
            type: 'primary',
            size: 'small',
            class: 'text-[13px]',
            onClick: () => handleToUpdate(row)
          },
          { default: () => '编辑' }
        ),
        !row.system &&
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'ml-2 text-[13px]',
              onClick: () => handleToDel(row)
            },
            { default: () => '删除' }
          )
      ])
    }
  }

  const staticColumns: DataTableColumns<RoleRowData> = [
    {
      title: '名称',
      key: 'name',
      minWidth: 120,
      width: 120,
      render: (row) => {
        return renderSort(() => renderRoleLabel(row.label, row.name))
      }
    },
    {
      title: '属性信息',
      key: 'system',
      minWidth: 120,
      width: 120,
      render(row) {
        return renderSystemLabel(row)
      }
    },
    {
      title: '描述',
      key: 'desc',
      minWidth: 120,
      width: 120
    },
    {
      title: '修改时间',
      key: 'updateTime',
      minWidth: 150,
      width: 150,
      render(row) {
        return formatTime(row.updateTime)
      }
    }
  ]

  // 判断用户是否具有编辑权限

  if (
    userStore.permissions?.some((item) => {
      return item === PERMISSIONS.ROLE_EDIT
    })
  ) {
    staticColumns.unshift(selectColumn)
    staticColumns.push(actionColumn)
  }

  return staticColumns
}

const checkedRowKeys = ref<string[]>([])

const columns = createColumns()

// 获取角色列表
const loadRoles = async () => {
  loading.value = true
  await getRoleByPage(pageInfo)
    .then((res) => {
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadRoles()
})

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
  loadRoles()
}

const handleSelectChange = (rows: string[]) => {
  checkedRowKeys.value = rows.map((item) => item)
}

// 去添加角色
const handleToAdd = () => {
  editModel.value = 'create'
}

const curRole = ref<RoleRes>()
// 去编辑角色
const handleToUpdate = (row: RoleRowData) => {
  editModel.value = 'update'
  curRole.value = row
}

// 去删除角色
const handleToDel = (row: RoleRowData) => {
  let dialogObj = dialog.warning({
    title: '你确定要删除这些角色吗？',
    class: '!w-[768px]',
    content: () =>
      h(
        PicValidCode,
        {
          showCloseIcon: false,
          class: '!w-full',
          onOnFinish: (picCode: string) => {
            load.show()
            delRole([row.id], picCode)
              .then(() => {
                message.success('删除角色成功')
                afterOpt()
                dialogObj.destroy()
              })
              .catch(console.error)
              .finally(() => {
                load.hide()
              })
          }
        },
        []
      )
  })
}

const handleAddRole = (data: RoleCreateReq) => {
  load.show()
  createRole(data)
    .then(() => {
      message.success('创建系统角色成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleUpdateRole = (data: RoleUpdateReq) => {
  load.show()
  updateRole(data)
    .then(() => {
      message.success('更新系统角色成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleAddAndUpdateRole = (type: number, data: RoleUpdateReq) => {
  if (type === 1) {
    handleUpdateRole(data as RoleUpdateReq)
  } else {
    handleAddRole({ ...data, type: 0 })
  }
}

const handleOrderChange = (newIndex: number, oldIndex: number) => {
  // 当前的顺序
  const ids = data.value.map((item) => item.id)
  const res = ids.splice(oldIndex, 1)
  ids.splice(newIndex, 0, ...res)
  sortRole(ids)
    .then(() => {
      afterOpt()
    })
    .catch(console.error)
}

// ================================= 角色新增和更新逻辑===============================================
const editModel = ref<'create' | 'update' | 'view'>('view')

const afterOpt = async () => {
  await loadRoles()
  editModel.value = 'view'
  roleStore.getRoleList()
}
</script>

<style scoped lang="scss">
.role-con {
  font-size: 13px;

  :deep(.n-data-table-tbody .n-data-table-tr:hover .n-data-table-td) {
    background-color: #e5f3ff;

    .move {
      opacity: 0.85;
    }
  }

  :deep(.my-handle) {
    height: 28px;
    line-height: 28px;
    // height: calc(100% + 16px);
    position: relative;
    .move {
      transition: all 0.3s var(--n-bezier);
      opacity: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #d1ecfa;
      color: $primaryColor;
      position: absolute !important;
      left: -8px;
      top: -8px;
      bottom: -8px;
      width: 40px;
      // right: 0;
      cursor: move;
    }
  }
}
</style>
